<template>
  <!-- 入库首页 -->
  <BaseHeader title="工兵第72旅机关信息资料室" />
  <div class="toptitlemain" v-loading="loading" element-loading-text="语音识别中">
    <div class="right">
      <div class="record-box">
        <!-- <el-select v-model="keyWord" filterable remote reserve-keyword placeholder="请输入关键词" clearable
          :remote-method="remoteMethod" :loading="loading" style="width: 240px" @change="handelSelectOne">
          <el-option v-for="item in books" :key="item.name" :label="item.name" :value="item.bookId" />
        </el-select> -->
        <div class="files">
          <div class="imgs">
            <el-upload class="avatar-uploader" :http-request="inportDatas" action="" accept=".png,.jpg,.jpeg"
              :show-file-list="false">

              <el-icon class="avatar-uploader-icon" color="#fff" size="24px">
                <Plus />
              </el-icon>
            </el-upload>
            <span style="font-size: 12px;color: #fff;">文件上传</span>
          </div>
          <div class="himgs" @click="handelPhotofn">
            <el-icon style="cursor: pointer;" color="#fff" size="24px">
              <Camera />
            </el-icon>
            <span style="font-size: 12px;color: #fff;">高拍仪上传</span>
          </div>
        </div>
        <div class="imgbox"
          style="width: 5vw; height: 8vh;margin-top: 1vh;display: flex;justify-content: center;margin-right: 5vw;margin-left: 1vw;">
          <el-image :preview-src-list="imageUrlList" v-if="imageUrl" :src="imageUrl" class="avatar"
            style="width: 100%;border: 1px dashed white;" />
          <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100%;"> -->
        </div>
        <el-input ref="barCodeInput" v-model="keyWord" @change="handelSelectOne" placeholder="请输入关键词" style="width: 240px"></el-input>
        <el-button @click="startRecord" type="primary" v-if="!isRecording">
          打开录音<el-icon class="Microphone">
            <Microphone />
          </el-icon>
        </el-button>
        <el-button @click="stopRecord" type="primary" v-else>
          结束录音<el-icon class="Microphone">
            <Microphone />
          </el-icon>
        </el-button>
        <audio v-if="localUrl" controls>
          <source :src="localUrl" />
        </audio>
      </div>
      <el-table :data="tables" class="my-custom-table" style="height: 60vh;">
        <el-table-column prop="name" label="书名" />
        <el-table-column prop="inventoryNum" label="库存" />
        <el-table-column prop="storageLocation" label="位置" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button :disabled="scope.row.inventoryNum == 0 ? true : false" type="primary" size="small"
              @click.prevent="borrowRow(scope.row)">
              请领
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginations">
        <el-pagination v-model:current-page="current" :page-size="size" :size="size" layout="total, prev, pager, next"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" background
          class="page" />
      </div>
      <BaseFooter />
    </div>
    <OpenPhoto :isShow="showPhoto" @confirm-box="confirmOpen" @close-box="showPhoto = false" />
  </div>
</template>

<script setup lang="ts">
import BaseHeader from '../BaseHeader.vue';
import BaseFooter from '../BaseFooter.vue';
import OpenPhoto from './components/qingling/OpenPhoto.vue';
import { uploadBill, getInStockList } from '../../../api/index'
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import Recorder from 'recorder-core'
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
//录制wav格式的用这一句就行
import 'recorder-core/src/engine/wav'
import 'recorder-core/src/extensions/waveview'
import { useRouter } from 'vue-router';
import request from "../../../utils/request";
const router = useRouter();
let showPhoto = ref(false);
let keyWord = ref();
let imageUrl = ref('');
let imageUrlList = ref<any>([]);
const rec = ref<any>();
let wave = ref<any>();
// let recBlob = ref<any>();
let isRecording = ref(false);
let localUrl = ref<any>();
// let wsUrl = ref('ws://localhost:8899');
// let ws = ref<any>();
let tables = ref<any>([]);
let size = ref(10);
let current = ref(1);
let total = ref(10)
const loading =ref(false)
const barCodeInput:any = ref(null);
onMounted(() => {
  barCodeInput.value.focus()
  // WebSocketTest(data);
})

const handleCurrentChange = (cur: number) => {
  current.value = cur;
  handelSelectOne(keyWord.value);
}

const handleSizeChange = (val: number) => {
  size.value = val;
  handelSelectOne(keyWord.value);
}

const inportDatas = (file: any) => {
  const foms = new FormData();
  foms.append('file', file.file);
  uploadBill(foms).then((res: any) => {
    if (res.code === 200) {
      imageUrl.value = res.data;
      let reader = new FileReader();
      reader.readAsDataURL(file.file);
      reader.onload = (e: any) => {
        imageUrl.value = e.target.result;
        imageUrlList.value[0] = e.target.result as any;
        imageUrlList.value[1] = e.target.result as any;
      }
      // this.onSubmit();
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const handelPhotofn = () => {
  showPhoto.value = true;
}

const confirmOpen = (val: string) => {
  showPhoto.value = false;
  if (val) {
    const imgs = `data:image/jpg;base64,${JSON.parse(val)}`;
    const formData = new FormData();
    formData.append('file', base64ToBlob(imgs)[0]);
    uploadBill(formData).then((res: any) => {
      if (res.code === 200) {
        imageUrl.value = imgs;
      } else {
        ElMessage.error(res.msg);
      }
    })
  }
}

// base64 转为Blob
const base64ToBlob = (base64Data: any) => {
  const dataArr = base64Data.split(','); // 根据,来分隔
  const imageType = dataArr[0].match(/:(.*?);/)[1]; // 获取文件类型。使用正则捕获 image/jpeg
  const textData = window.atob(dataArr[1]); // 使用atob() 将base64 转为文本文件
  const arrayBuffer = new ArrayBuffer(textData.length); // 创建一个二进制数据缓冲区，可以理解为一个数组
  const uint8Array = new Uint8Array(arrayBuffer); // 创建一个类型化数组对象，可以理解为上面的数组的成员，给这个对象赋值就会放到上面的数组中。
  for (let i = 0; i < textData.length; i++) {
    uint8Array[i] = textData.charCodeAt(i); // 将文本文件转为UTF-16的ASCII, 放到类型化数组对象中
  }
  return [new Blob([arrayBuffer], { type: imageType }), imageType.slice(6)]; // 返回两个值，一个Blob对象，一个图片格式（如jpeg）
}

// 开始录音
const startRecord = () => {

  if (imageUrl.value === '') {
    return ElMessage.error('请先上传单据')
  }
  ElMessage.info('正在打开麦克风，请稍后')
  rec.value = Recorder({
    type: "wav" //录音格式，可以换成wav等其他格式
    , sampleRate: 16000 //录音的采样率，越大细节越丰富越细腻
    , bitRate: 16 //录音的比特率，越大音质越好
    , onProcess: (buffers: any, powerLevel: any, bufferSampleRate: any) => {
      //录音实时回调，大约1秒调用12次本回调
      //可实时绘制波形，实时上传（发送）数据
      wave.value = buffers[buffers.length - 1], powerLevel, bufferSampleRate
      // console.log(buffers)
      // console.log(powerLevel)
      // console.log(bufferSampleRate)
    }
  });
  rec.value.open(() => {
    rec.value.start();
    isRecording.value = true;
    ElMessage.success('麦克风已打开')
  }, (msg: any) => {
    ElMessage.error("无法录音:" + msg)
  });
}

// const blobToBase64 = (blob: any) => {
//   return new Promise((resolve: any) => {
//     const reader = new FileReader()
//     reader.readAsDataURL(blob)
//     reader.onload = (e: any) => {
//       resolve(e.target.result)
//     }
//   })
// }

// 关闭录音
const stopRecord = () => {
  if (imageUrl.value === '') {
    return ElMessage.error('请先上传单据')
  }
  // if(!rec.value){ console.error("未打开录音");return }

  // speechRecognize({audio:})
  rec.value.stop(async (blob: any) => {
    console.log(blob)
    loading.value=true
    const formData = new FormData();
      formData.append('audio', blob);
  request.post('/speech/recognize', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(response => {
    // 处理响应
    console.log(response);
    keyWord.value=response
    handelSelectOne(keyWord.value)
    loading.value=false
  })
  .catch(error => {
    // 处理错误
    console.error(error);
  });
    
 
   
    rec.value.close();//关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
    rec.value = null;
    isRecording.value = false;
    ElMessage.info('关闭麦克风');
  }, (err: any) => {
    console.error("结束录音出错：" + err);
    rec.value.close();//关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
    rec.value = null;
  });
}

// 选中后
const handelSelectOne = (val: any) => {
  const params = {
    size: size.value,
    current: current.value,
    name: val
  }
  getInStockList(params).then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.total;
      tables.value = res.data.records.map((el: any) => {
        el.storageLocation = el.storageLocations.join(',')
        // el.name = books.value.find((item:any)=>item.bookId === val).name;
        return el
      });
    }
  })
}

// 请领
const borrowRow = (row: any) => {
  if (!imageUrl.value) {
    return ElMessage.error('请先上传单据');
  }
  router.push({
    name: 'borrow',
    params: {
      id: row.bookId,
      name: row.name,
      miji: row.classification,
      inventoryNum: row.inventoryNum,
      publishTime: row.publicationTime,
      img: imageUrl.value
    }
  })
}

// 连接socket
// const WebSocketTest = (data: any) => {
//   if ("WebSocket" in window) {
//     // 打开一个 web socket
//     ws.value = new WebSocket(wsUrl.value);
//     ws.value.onopen = () => {
//       // Web Socket 已连接上，使用 send() 方法发送数据
//       // this.fileVbse(data);
//       let pame: any = {
//         type: 'checkin',
//         stockID: 'sssss'
//       }
//       console.log(`${JSON.stringify(pame)}|` + data);
      
//       ws.value.send(`${JSON.stringify(pame)}|` + data);
//     }
//     ws.value.onmessage = function (evt: any) {
//       var received_msg = evt.data;
//       if (received_msg) {
//         keyWord.value = received_msg;
//       } else {

//       }
//       console.log(received_msg, 'received_msg')
//       // alert("数据已接收...");
//     };

//     ws.value.onclose = function () {
//       // 关闭 websocket
//       // alert("连接已关闭...");
//     };
//   } else {
//     // 浏览器不支持 WebSocket
//     alert("您的浏览器不支持 WebSocket!");
//   }
// }


</script>

<style scoped lang="less">
.read-the-docs {
  color: #888;
}

.toptitlemain {
  position: relative;
  width: 100vw;
  display: flex;
  align-content: center;
  flex-wrap: nowrap;
  box-sizing: border-box;
  padding: 1vh 1vw 0;
  height: 83vh;
  background-color: rgb(23, 41, 76);

  .left {
    width: 34vw;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px 20px;
    box-sizing: border-box;
    margin-right: 1vw;


  }

  .files {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
    float: left;

    &::before {
      content: "*";
      color: red;
      margin-right: 10px;
    }

    .imgs {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-direction: column;
      margin-right: 20px;
      height: 50px;
    }
  }

  .himgs {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: column;
    height: 50px;

    i {
      line-height: 28px;
    }
  }

  .right {
    width: 100vw;
    background-color: rgb(23, 41, 76);
    border-radius: 10px;
    padding: 0px 20px 10px;
    box-sizing: border-box;

    .record-box {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: row;
      flex-wrap: nowrap;

      .el-button {
        margin-left: 10px;
      }
    }



  }
}

.paginations {
  position: fixed;
  right: 0;
  left: 0;
  bottom: 15vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .page {
    margin-right: 10px;
  }
}
</style>
